﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Super.Hmi.Assets.CustomControl
{
    /// <summary>
    /// MenuItemControl.xaml 的交互逻辑
    /// </summary>
    public partial class MenuItemControl : UserControl, INotifyPropertyChanged
    {
        #region 依赖属性

        public double HorizontalOffset
        {
            get { return (double)GetValue(HorizontalOffsetProperty); }
            set { SetValue(HorizontalOffsetProperty, value); }
        }
        public static readonly DependencyProperty HorizontalOffsetProperty =
            DependencyProperty.Register("HorizontalOffset", typeof(double), typeof(MenuItemControl), new PropertyMetadata(0d));

        public double VerticalOffset
        {
            get { return (double)GetValue(VerticalOffsetProperty); }
            set { SetValue(VerticalOffsetProperty, value); }
        }
        public static readonly DependencyProperty VerticalOffsetProperty =
            DependencyProperty.Register("VerticalOffset", typeof(double), typeof(MenuItemControl), new PropertyMetadata(0d));

        // 定义 ItemSource 依赖属性
        public static readonly DependencyProperty ItemSourceProperty =
        DependencyProperty.Register("ItemSource", typeof(IEnumerable), typeof(MenuItemControl), new PropertyMetadata(null));

        public IEnumerable ItemSource
        {
            get => (IEnumerable)GetValue(ItemSourceProperty);
            set => SetValue(ItemSourceProperty, value);
        }

        // 定义 PlacementTarget 依赖属性
        public static readonly DependencyProperty PlacementTargetProperty =
        DependencyProperty.Register("PlacementTarget", typeof(UIElement), typeof(MenuItemControl), new PropertyMetadata(null));

        public UIElement PlacementTarget
        {
            get => (UIElement)GetValue(PlacementTargetProperty);
            set => SetValue(PlacementTargetProperty, value);
        }

        public PlacementMode Placement
        {
            get { return (PlacementMode)GetValue(PlacementProperty); }
            set { SetValue(PlacementProperty, value); }
        }

        public static readonly DependencyProperty PlacementProperty =
            DependencyProperty.Register("Placement", typeof(PlacementMode), typeof(MenuItemControl), new PropertyMetadata(PlacementMode.Right));

        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }

        public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register("Command", typeof(ICommand), typeof(MenuItemControl), new PropertyMetadata(default(ICommand)));
        public object CommandParemter
        {
            get { return (object)GetValue(CommandParemterProperty); }
            set { SetValue(CommandParemterProperty, value); }
        }

        public static readonly DependencyProperty CommandParemterProperty =
        DependencyProperty.Register("CommandParemter", typeof(object), typeof(MenuItemControl), new PropertyMetadata(null));

        public bool IsOpenMneu
        {
            get { return (bool)GetValue(IsOpenMneuProperty); }
            set { SetValue(IsOpenMneuProperty, value); }
        }

        public static readonly DependencyProperty IsOpenMneuProperty =
        DependencyProperty.Register("IsOpenMneu", typeof(bool), typeof(MenuItemControl), new PropertyMetadata(false, new PropertyChangedCallback(OnIsOpneMenuChanged)));

        private static void OnIsOpneMenuChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as MenuItemControl;
            control._isParentMouseOver = (bool)e.NewValue;
            if ((bool)e.NewValue)
            {
                control.IsOpen = true;
            }
            else
                control._timer.Enabled = true;
        }

        #endregion

        private bool _isOpen;
        public bool IsOpen
        {
            get { return _isOpen; }
            set
            {
                _isOpen = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsOpen"));
            }
        }

        private bool _isPopupMouseOver = false;
        private bool _isParentMouseOver = false;
        private System.Timers.Timer _timer;
        public event PropertyChangedEventHandler? PropertyChanged;
        public MenuItemControl()
        {
            InitializeComponent();
            _timer = new System.Timers.Timer();
            _timer.Interval = 20;
            _timer.Elapsed += _timer_Elapsed;
            _timer.AutoReset = false;
        }
        private bool HasChildOpen()
        {
            List<MenuItemControl> popups = new List<MenuItemControl>();
            this.Dispatcher.BeginInvoke(() =>
            {
                var allControls = FindVisualChildren(this); // this 指当前UserControl实例
                foreach (var control in allControls)
                {
                    if (control is MenuItemControl menuItem)
                    {
                        if (menuItem.ItemSource != null && (menuItem.ItemSource as ICollection).Count != 0)
                            popups.Add(menuItem);
                    }
                }
            }).Wait();
            bool isHasChild = popups.Where(p => p.IsOpen).Count() > 0;
            return isHasChild;
        }
        private void _timer_Elapsed(object? sender, ElapsedEventArgs e)
        {
            _timer.Enabled = false;
            if (!HasChildOpen() && !_isParentMouseOver && !_isPopupMouseOver)
            {
                IsOpen = false;
                return;
            }
            _timer.Enabled = true;
        }

        public static List<FrameworkElement> FindVisualChildren(DependencyObject parent)
        {
            var children = new List<FrameworkElement>();
            if (parent == null) return children;
            // 1. 特殊处理 Popup 控件
            if (parent is Popup popup && popup.Child != null)
            {
                // 添加 Popup 的 Child 是 MenuItemControl 本身
                if (popup.Child is MenuItemControl popupChild)
                {
                    children.Add(popupChild);
                }
                // 递归处理 Popup 的内容
                children.AddRange(FindVisualChildren(popup.Child));
            }
            // 2. 处理普通可视化树
            try
            {
                int childCount = VisualTreeHelper.GetChildrenCount(parent);
                for (int i = 0; i < childCount; i++)
                {
                    var child = VisualTreeHelper.GetChild(parent, i);
                    // 处理 MenuItemControl
                    if (child is MenuItemControl element)
                    {
                        children.Add(element);
                    }
                    // 3. 递归处理子元素（包括非 FrameworkElement）
                    children.AddRange(FindVisualChildren(child));
                }
            }
            catch (ArgumentException)
            {
                // 忽略已卸载元素的异常
            }
            return children;
        }
        private void PopupBorder_MouseEnter(object sender, MouseEventArgs e)
        {
            _isPopupMouseOver = true;
            _timer.Enabled = false; // 停止计时器
        }
        private void PopupBorder_MouseLeave(object sender, MouseEventArgs e)
        {
            _isPopupMouseOver = false;
            _timer.Enabled = true; // 开始计时器
        }
    }
}
